﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LIMS.Entities;
using LIMS.Shared;
namespace LIMS.Windows
{
    public partial class DepartmentManagement:LIMSPageBase<DepartmentManagementPresenter>,IDepartmentManagementPageView
    {
        public DepartmentManagement()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Enable disable form controls on action basis.
        /// if bValue is true contrlos will be enabled else disabled.
        /// </summary>
        /// </summary>
        private void bindDropDown()
        {
            try
            {

                bindStatus();
                bindPlant();
            }
            catch (Exception ex)
            {
                Logger.Error("error while binding drop down ");
            }
        }

        private void bindPlant()
        {
            Plant oPlant = new Plant();
            List<Plant> oPlantList = new List<Plant>();
            oPlant.Name = "--Select--";
            oPlant.Id = 0;
            oPlantList = this.Presenter.GetAllPlants();
            oPlantList.Insert(0, oPlant);         
            cmbPlantName.DataSource = oPlantList;
            cmbPlantName.ValueMember = "Id";
            cmbPlantName.DisplayMember = "Name";


        }

        private void bindStatus()
        {
            cmbStatus.DataSource = Resource.BindStatus();
            cmbStatus.DisplayMember = "StatusValue";
            cmbStatus.ValueMember = "StatusKey";
        }


        /// if bValue is true contrlos will be enabled else disabled.
        /// </summary>
        /// <param name="bValue"></param>
        private void EnableDisableControls(bool bValue)
        {
            try
            {
                txtDeptLocation.Enabled = bValue;
                txtDeptName.Enabled = bValue;
                cmbStatus.Enabled = bValue;
                cmbPlantName.Enabled = bValue;
                btnSaveDept.Enabled = bValue;
                btnClear.Enabled = bValue;
            }
            catch (Exception ex)
            { }
        }



        /// <summary>
        /// GetPlantBasedOnCriteria
        /// </summary>
        /// <param name="p_sCriteria"></param>
        private void GetDepartmentBasedOnCriteria(string p_sCriteria)
        {
            try
            {
                if (txtSearch.Text.Trim().Length == 0)
                {
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }
                else
                {
                    this.Presenter.SearchDepartmentByKeyword(p_sCriteria);
                    DisplayGrid();
                }
                //DisplayGrid();
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }
        /// <summary>
        /// grdSite_CellClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void grdDepartment_CellClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    bool bChkBoxSelected = false;
        //    int iDepartmentID = Convert.ToInt32(grdDepartment.Rows[grdDepartment.CurrentRow.Index].Cells["Id"].Value);
        //    m_DepartmentId = iDepartmentID;
        //    for (int iRowCount = 0; iRowCount < grdDepartment.Rows.Count; iRowCount++)
        //    {
        //        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdDepartment.Rows[iRowCount].Cells[0];
        //        if (cell is DataGridViewCheckBoxCell)
        //        {
        //            if ((bool)cell.EditedFormattedValue)
        //            {
        //                bChkBoxSelected = true;
        //                break;
        //            }
        //        }
        //    }
        //    if (bChkBoxSelected)
        //    {
        //        btnDelete.Enabled = true;
        //        btnEdit.Enabled = true;
        //    }
        //}



       

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdDepartment_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            bool bChkBoxSelected = false;
            int iDepartmentID = Convert.ToInt32(grdDepartment.Rows[grdDepartment.CurrentRow.Index].Cells["Id"].Value);
            m_DepartmentId = iDepartmentID;

            for (int iRowCount = 0; iRowCount < grdDepartment.Rows.Count; iRowCount++)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdDepartment.Rows[iRowCount].Cells[0];
                if (cell is DataGridViewCheckBoxCell)
                {
                    if ((bool)cell.EditedFormattedValue)
                    {
                        bChkBoxSelected = true;
                        break;
                    }
                }
            }
            if (bChkBoxSelected)
            {
                btnDelete.Enabled = true;
                btnEdit.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
                btnEdit.Enabled = false;
            }

        }
        private static int m_DepartmentId = 0;
        /// <summary>
        /// btnEdit_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (m_DepartmentId > 0)
            {
                int iSelectedRowsCount = 0;
                int iRowIndex = 0;
                for (int iRowCount = 0; iRowCount < grdDepartment.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdDepartment.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iRowIndex = iRowCount;
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount > 1)
                {
                    MessageBox.Show("Select single row to edit the record.");
                    return;
                }
                else if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to edit.");
                    return;
                }

                /// Edit
                CurrentIndex = iRowIndex;
                EnableDisableControls(true);
                btnClear.Enabled = false;
            }
        }
        /// <summary>
        /// btnDelete_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (m_DepartmentId > 0)
            {
                int iSelectedRowsCount = 0;
                for (int iRowCount = 0; iRowCount < grdDepartment.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdDepartment.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to delete.");
                    return;
                }

                DialogResult oResult = MessageBox.Show("Are you sure to delete the selected records?", "Delete site", MessageBoxButtons.YesNo);
                if (oResult.Equals(DialogResult.Yes))
                {
                    /// Delete
                    for (int iRowCount = 0; iRowCount < grdDepartment.Rows.Count; iRowCount++)
                    {
                        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdDepartment.Rows[iRowCount].Cells[0];
                        if (cell is DataGridViewCheckBoxCell)
                        {
                            if ((bool)cell.EditedFormattedValue)
                            {
                                this.Presenter.Delete(oDepartments[iRowCount]);
                            }
                        }
                    }
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }

            }
        }

        /// <summary>
        /// DisplayGrid
        /// </summary>
        private void DisplayGrid()
        {

            if (grdDepartment.Columns[0].Displayed == false)
            {
                DataGridViewCheckBoxColumn oChkColumn = new DataGridViewCheckBoxColumn(false);

                oChkColumn.HeaderText = "Select";
                oChkColumn.Name = "Select";
                oChkColumn.Width = 50;

                grdDepartment.Columns.Insert(0, oChkColumn);
            }

            grdDepartment.MultiSelect = false;
            grdDepartment.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdDepartment.AllowUserToAddRows = false;

            foreach (DataGridViewColumn dc in grdDepartment.Columns)
            {
                if (dc.Index.Equals(0))
                {
                    dc.ReadOnly = false;
                }
                else
                {
                    dc.ReadOnly = true;
                }
            }
            grdDepartment.RowHeadersVisible = false;
        }
        /// <summary>
        /// btnSaveSite_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveDept_Click(object sender, EventArgs e)
        {
            try
            {
                if (Validations.IsEmpty(txtDeptLocation.Text.Trim()) || Validations.IsEmpty(txtDeptName.Text.Trim()) ||
                    Validations.IsCmbboxDefaultValue(Convert.ToString(cmbStatus.SelectedValue)) || Validations.IsCmbboxDefaultValue(Convert.ToString(cmbPlantName.SelectedValue)))
                {
                    MessageBox.Show("Fill mandatory(*) information.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

                else
                {
                    oDepartments[CurrentIndex].Name = txtDeptName.Text;
                    oDepartments[CurrentIndex].Location = txtDeptLocation.Text;
                    oDepartments[CurrentIndex].PlantId = Convert.ToInt32(cmbPlantName.SelectedValue);
                    oDepartments[CurrentIndex].Status = Convert.ToString(cmbStatus.SelectedValue);
                    oDepartments[CurrentIndex].CreatedBy = 1; /// logged in user
                    oDepartments[CurrentIndex].CreatedDateTime = DateTime.Now;


                    ///save site.
                    if (this.Presenter.Save(oDepartments[CurrentIndex]))
                    {
                        MessageBox.Show("Department saved successfully.");
                        EnableDisableControls(false);
                        btnEdit.Enabled = false;
                        btnDelete.Enabled = false;
                        ClearData();
                    }
                    ///intialize grid after saving site..
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while saving site .");
            }
        }

        private void ClearData()
        {
            txtDeptName.Text = string.Empty;
            txtDeptLocation.Text = string.Empty;
            cmbStatus.SelectedValue = "X";
            cmbPlantName.SelectedValue = 0;
        }

        #region IPlantManagementPageView Members
        /// <summary>
        /// iCurrentIndex
        /// </summary>
        private int iCurrentIndex;
        public int CurrentIndex
        {
            set
            {
                iCurrentIndex = value;
                txtDeptName.Text = oDepartments[iCurrentIndex].Name;
                txtDeptLocation.Text = oDepartments[iCurrentIndex].Location;
                cmbPlantName.SelectedValue = oDepartments[iCurrentIndex].PlantId;
                cmbStatus.SelectedValue = oDepartments[CurrentIndex].Status;

            }
            get
            {
                return iCurrentIndex;
            }
        }
        /// <summary>
        /// FillPageData
        /// </summary>
        public void FillPageData()
        {
        }

        /// <summary>
        /// GridViewData
        /// </summary>
        private GridViewData oGridData;
        public GridViewData GridData
        {
            set
            {
                oGridData = value;
                lblTotal.Text = "/ " + (value.TotalRecords / value.PageSize + ((value.TotalRecords % value.PageSize > 0) ? 1 : 0)).ToString();
                txtPageNo.Text = value.PageIndex.ToString();
            }
            get
            {
                if (oGridData != null)
                {
                    return oGridData;
                }
                else
                {
                    GridViewData grdData = new GridViewData();
                    grdData.SortOrder = "ASC";
                    grdData.SortColumn = "CreatedDateTime";
                    grdData.PageSize = 10;//SetGridPageSize();
                    grdData.PageIndex = 1;
                    return grdData;
                }

            }
        }
        /// <summary>
        /// ShowMessage
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sMessage"></param>
        public void ShowMessage(MessageType type, string sMessage)
        {
            //throw new NotImplementedException();
        }

        private List<Department> oDepartments;
        public List<Department> Departments
        {
            get
            {
                if (oDepartments == null)
                {
                    oDepartments = new List<Department>();
                }
                return oDepartments;
            }
            set
            {
                oDepartments = value;
                grdDepartment.DataSource = ConvertListToDataTable(oDepartments);
                grdDepartment.Columns[0].Visible = false;
            }
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddNewDept_Click(object sender, EventArgs e)
        {
            EnableDisableControls(true);
            txtDeptName.Focus();
            Department  newDepartment = new Department ();
            oDepartments.Add(newDepartment);
            
            CurrentIndex = oDepartments.Count - 1;
            cmbStatus.SelectedIndex = 0;

        }
        /// <summary>
        /// ConvertListToDataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private DataTable ConvertListToDataTable(List<Department> list)
        {
            try
            {

                DataTable table = new DataTable();
                DataColumn oColumn0 = new DataColumn("Id", typeof(int));
                DataColumn oColumn1 = new DataColumn("Name", typeof(string));
                DataColumn oColumn2 = new DataColumn("Location", typeof(string));
                DataColumn oColumn3 = new DataColumn("PlantName", typeof(string));
                DataColumn oColumn4 = new DataColumn("Status", typeof(string));

                //DataColumn oColumn5 = new DataColumn("Email", typeof(string));
                table.Columns.Add(oColumn0);
                table.Columns.Add(oColumn1);
                table.Columns.Add(oColumn2);
                table.Columns.Add(oColumn3);
                table.Columns.Add(oColumn4);


                for (int i = 0; i < list.Count; i++)
                {
                    DataRow oNewRow = table.NewRow();
                    oNewRow["Id"] = list[i].Id;
                    oNewRow["Name"] = list[i].Name;
                    oNewRow["Location"] = list[i].Location;
                    oNewRow["PlantName"] = list[i].PlantName;
                    oNewRow["Status"] = SharedResource.GetCodedStatus(list[i].Status);

                    table.Rows.Add(oNewRow);
                }
                return table;
            }

            catch (Exception ex)
            {
                Logger.Error("error while Convert List To DataTable in plant managment" + ex.ToString());
                return null;
            }
        }
        #endregion



      



        /// <summary>
        /// btnSearch_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string sCriteria = txtSearch.Text.Trim();
            if (sCriteria.Length > 0)
            {
                if (sCriteria.Contains("*"))
                {
                    if (sCriteria.Equals("*"))
                    {
                        sCriteria = string.Empty;
                    }
                    else
                    {
                        sCriteria = sCriteria.Replace("*", "%");
                    }
                }
                else if (sCriteria.Contains("?"))
                {
                    sCriteria = sCriteria.Replace("?", "%");
                }
            }
            GetDepartmentBasedOnCriteria(sCriteria);
            ClearData();
        }
        /// <summary>

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            try
            {
                if (GridData.PageIndex > 1)
                {
                    GridData.PageIndex--;
                    GetDepartmentBasedOnCriteria(string.Empty);
                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }

        }


        private void btnLast_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                GetDepartmentBasedOnCriteria(string.Empty);
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnSpecific_Click(object sender, EventArgs e)
        {
            try
            {
                int userCurrentPage = 0;

                if (!int.TryParse(txtPageNo.Text, out userCurrentPage))
                {
                    userCurrentPage = 1;
                }

                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                if (userCurrentPage > maxPageSize)
                {
                    userCurrentPage = 1;
                }
                GridData.PageIndex = userCurrentPage;
                GetDepartmentBasedOnCriteria(string.Empty);
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) - 1);

                if (GridData.PageIndex <= maxPageSize)
                {
                    GridData.PageIndex++;
                    GetDepartmentBasedOnCriteria(string.Empty);
                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = 1;//(GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) -1 );
                GetDepartmentBasedOnCriteria(string.Empty);
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        private void DepartmentManagement_Load(object sender, EventArgs e)
        {
            oGridData = null;
            bindDropDown();
            GridPagingToolTip();
            this.Presenter.InitializeView();
            DisplayGrid();
            EnableDisableControls(false);
            btnDelete.Enabled = false;
            btnEdit.Enabled = false;
        }

        private void GridPagingToolTip()
        {
            System.Windows.Forms.ToolTip ToolTipText = new System.Windows.Forms.ToolTip();
            ToolTipText.SetToolTip(this.btnNext, "Next");
            ToolTipText.SetToolTip(this.btnFirst, "First");
            ToolTipText.SetToolTip(this.btnPrevious, "Previous");
            ToolTipText.SetToolTip(this.btnLast, "Last");
            ToolTipText.SetToolTip(this.btnSpecific, "Go to specific");
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearData();
        }

    
       

       
        
    }
}
